package com.syj.qdp.framework.security.core.handler;

import com.syj.qdp.framework.common.pojo.CommonResult;
import com.syj.qdp.framework.common.util.servlet.ServletUtils;
import com.syj.qdp.framework.security.config.SecurityProperties;
import com.syj.qdp.framework.security.core.service.SecurityAuthFrameworkService;
import com.syj.qdp.framework.web.util.WebFrameworkUtils;
import com.syj.qdp.framework.security.core.util.SecurityFrameworkUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.syj.qdp.framework.common.pojo.CommonResult.success;

/**
 * 默认的 用户进行注销时处理器
 *
 * @author Lyon
 */
@Slf4j
public class DefaultLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    SecurityProperties securityProperties;
    @Resource
    SecurityAuthFrameworkService securityAuthFrameworkService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = SecurityFrameworkUtils.obtainAuthorizationToken(request, securityProperties.getTokenHeader());
        log.info("[commendce] 用户[{}]注销登录.", WebFrameworkUtils.getLoginUserId());
        securityAuthFrameworkService.logout(token);
        ServletUtils.writeJSON(response, CommonResult.success());
    }

}
